package com.eagle.util;

import cn.hutool.core.io.IoUtil;
import com.eagle.constant.Constant;
import com.eagle.entity.ExcelTemplate;
import com.eagle.entity.MavenDependency;
import com.google.common.collect.Ordering;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author qinlinsen
 */
public class FileUtil {
    public static Set<MavenDependency> readFileFrom(Path sourceFile) throws IOException {
        Objects.requireNonNull(sourceFile);
        Stream<String> lines = Files.lines(sourceFile);
        List<MavenDependency> dependencyList = lines.filter(StringUtil::isValidMavenDependencyStr)
                .map(StringUtil::toMavenDependencyFrom)
                .distinct()
                .collect(Collectors.toList());
        HashSet<MavenDependency> mavenDependencies = new HashSet<>(dependencyList);
        return mavenDependencies;
    }


    public static void writeToTemplateExcel(final Collection<MavenDependency> datum,
                                            final String sheetName,
                                            final String templateExcelFileAbsolutePath,
                                            final int startRowNum,
                                            final ExcelTemplate excelTemplate) throws IOException{
        Objects.requireNonNull(datum);
        Objects.requireNonNull(templateExcelFileAbsolutePath);
        FileInputStream in = null;
        XSSFWorkbook workbook = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(templateExcelFileAbsolutePath);
            workbook = new XSSFWorkbook(in);
            XSSFSheet sheet = workbook.getSheet(sheetName);
            final AtomicInteger adder = new AtomicInteger(0);

            datum.stream()
                    .sorted(Ordering.from((Comparator<MavenDependency>) (o1, o2) -> o1.getGroupId().compareTo(o2.getGroupId()))
                            .compound((o1, o2) -> o1.getArtifactId().compareTo(o2.getGroupId())))
                    .forEach(mavenDependency -> {
                        XSSFRow row = sheet.createRow(startRowNum + adder.getAndIncrement());
                        initCellValue(excelTemplate, mavenDependency, row);
                    });
            out = new FileOutputStream(templateExcelFileAbsolutePath);
            workbook.write(out);
        }finally {
            IoUtil.close(in);
            IoUtil.close(workbook);
            IoUtil.close(out);
        }
    }

    private static void initCellValue(ExcelTemplate excelTemplate, MavenDependency mavenDependency, XSSFRow row) {
        //第0个单元格
        XSSFCell zeroCell = row.createCell(0);
        zeroCell.setCellValue(Constant.EMPTY_STRING);
        //第1个单元格
        XSSFCell departmentCell = row.createCell(1);
        departmentCell.setCellValue(excelTemplate.getDepartment());

        //第2个单元格
        XSSFCell principalCell = row.createCell(2);
        principalCell.setCellValue(excelTemplate.getPrincipal());

        //第3个单元格
        XSSFCell systemNameCell = row.createCell(3);
        systemNameCell.setCellValue(excelTemplate.getSystemName());

        //第4个单元格
        XSSFCell ipAddressCell = row.createCell(4);
        final String ipAddress = excelTemplate.getIpAddress();
        ipAddressCell.setCellValue(Objects.nonNull(ipAddress) ? ipAddress : Constant.EMPTY_STRING);

        //第5个单元格
        XSSFCell fifthCell = row.createCell(5);
        fifthCell.setCellValue(mavenDependency.getGroupId() + ":" + mavenDependency.getArtifactId());

        //第6个单元格
        XSSFCell currentVersionCell = row.createCell(6);
        currentVersionCell.setCellValue(mavenDependency.getVersion());

        //第7个单元格:
        XSSFCell latestVersionCell = row.createCell(7);
        final String latestVersion = excelTemplate.getLatestDependencyVersion();
        latestVersionCell.setCellValue(Objects.nonNull(latestVersion) ? latestVersion : Constant.EMPTY_STRING);

        //第8个单元格:
        XSSFCell remarkCell = row.createCell(8);
        final String remark = excelTemplate.getRemark();
        remarkCell.setCellValue(Objects.nonNull(remark) ? remark : Constant.EMPTY_STRING);
    }


    public static void main(String[] args) throws Exception {
        Set<MavenDependency> result = readFileFrom(Paths.get("D:\\idea-projects\\demo-projects\\jar-version-statistics\\src\\main\\resources\\jar-version.txt"));
        System.out.println(result);
    }
}
